import 'dart:typed_data';
import 'dart:io';
import 'package:epubx/epubx.dart' hide EpubChapter;
import '../models/book.dart';

Future<List<EpubChapter>> parseEpubChapters(Book book) async {
  Uint8List? bytes;
  if (book.isTemp && identical(0, 0.0)) {
    // kIsWeb 不能直接用，这里仅示例
    // 你可以在主代码里传递kIsWeb判断
    // bytes = _WebTempEpubHolder.bytes;
    return [];
  } else if (book.path != null) {
    try {
      final file = File(book.path!);
      bytes = await file.readAsBytes();
    } catch (_) {
      return [];
    }
  }
  if (bytes == null) return [];

  final epubBook = await EpubReader.readBook(bytes);

  List<EpubChapter> chapters = [];
  for (final chapter in epubBook.Chapters!) {
    if (chapter.HtmlContent != null && chapter.HtmlContent!.isNotEmpty) {
      final text = removeHtmlTags(chapter.HtmlContent!);
      chapters.add(
        EpubChapter(title: chapter.Title ?? '章节', textContent: text),
      );
    } else if (chapter.SubChapters != null && chapter.SubChapters!.isNotEmpty) {
      for (final sub in chapter.SubChapters!) {
        if (sub.HtmlContent != null && sub.HtmlContent!.isNotEmpty) {
          final imgSrcs =
              RegExp(r'<img[^>]+src="([^"]+)"')
                  .allMatches(sub.HtmlContent!)
                  .map((m) => m.group(1))
                  .whereType<String>()
                  .toList();
          List<Uint8List> images = [];
          for (final src in imgSrcs) {
            final img = epubBook.Content?.Images?[src];
            if (img != null) images.add(Uint8List.fromList(img.Content!));
          }
          chapters.add(EpubChapter(title: sub.Title ?? '图片章节', images: images));
        }
      }
    }
  }
  return chapters;
}

String removeHtmlTags(String html) {
  return RegExp(r'<[^>]+>')
      .allMatches(html)
      .fold(html, (prev, match) => prev.replaceAll(match.group(0)!, ''));
}
